package com.demo.servlet;

import com.demo.bean.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.Map;

/**
 * @author WuLiangHang
 */
@WebServlet("/user.do")
public class UserServlet extends BaseServlet {
    public void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取登录的用户名
        String username = req.getParameter("username");
        //从ServletContext中获取在线名单
        Map<String, User> onlineUsers = (Map<String, User>) this.getServletContext().getAttribute("onlineUsers");
        //如果在线名单存在
        if (onlineUsers != null) {
            //如果在线名单中已经存在这个用户名
            if (onlineUsers.containsKey(username)) {
                //转发到登录页面 显示错误信息
                req.setAttribute("msg", "用户" + username + "已经登录!");
                req.getRequestDispatcher("/login.jsp").forward(req, resp);
                return;
            }
        }
        //获取ip地址
        String ip = req.getRemoteAddr();
        //获取登录时间
        String loginTime = String.format("%tF %<tT", new Date());
        //创建User对象
        User user = new User(username, ip, loginTime);
        //把User对象保存到Session中
        //这时会执行监听器attributeAdded() attributeReplaced()方法
        req.getSession().setAttribute("user", user);
        //设置当前用户的Session
        user.setSession(req.getSession());
        //重定向到user.jsp显示在线用户名单
        resp.sendRedirect(req.getContextPath() + "/users.jsp");
    }

    public void quit(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getSession().removeAttribute("user");
        resp.getWriter().print("退出成功");
    }

    public void kick(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String ip = req.getRemoteAddr();
        if (!"0:0:0:0:0:0:0:1".equals(ip)) {
            resp.getWriter().print("你没有踢人的权限");
            return;
        }
        String username = req.getParameter("username");
        User currentUser = (User) req.getSession().getAttribute("user");
        //如果当前用户就是被踢用户 就是自己踢自己
        if (currentUser.getName().equals(username)) {
            resp.getWriter().print("不能踢自己");
            return;
        }
        //从在线名单中获取被踢的用户
        Map<String, User> onlineUsers = (Map<String, User>) this.getServletContext().getAttribute("onlineUsers");
        User user = onlineUsers.get(username);
        user.getSession().removeAttribute("user");
        resp.sendRedirect(req.getContextPath() + "/users.jsp");
    }
}
